using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace WeChatFileManagementWinApp
{
    /// <summary>
    /// 微信文件搜索器，负责搜索和管理微信文件
    /// </summary>
    public class WeChatFileSearcher
    {
        // 用于匹配 FileStorage\File\YYYY-MM 模式的正则表达式
        private static readonly Regex DateDirectoryRegex = new Regex(@"FileStorage\\File\\\d{4}-\d{2}$", RegexOptions.IgnoreCase);

        private readonly List<string> _searchDirectories;
        private readonly List<WeChatFile> _foundFiles;

        /// <summary>
        /// 搜索进度变更事件
        /// </summary>
        public event EventHandler<ProgressChangedEventArgs> ProgressChanged;

        /// <summary>
        /// 初始化微信文件搜索器
        /// </summary>
        /// <param name="directories">要搜索的目录列表</param>
        public WeChatFileSearcher(List<string> directories)
        {
            _searchDirectories = directories ?? new List<string>();
            _foundFiles = new List<WeChatFile>();
        }

        /// <summary>
        /// 获取已找到的文件列表
        /// </summary>
        public IReadOnlyList<WeChatFile> FoundFiles => _foundFiles.AsReadOnly();

        /// <summary>
        /// 搜索微信文件
        /// </summary>
        public void SearchWeChatFiles()
        {
            _foundFiles.Clear();
            
            if (!_searchDirectories.Any())
            {
                OnProgressChanged(0, "没有配置搜索目录");
                return;
            }

            int totalDirectories = _searchDirectories.Count;
            for (int i = 0; i < totalDirectories; i++)
            {
                string directory = _searchDirectories[i];
                // 报告搜索进度
                int percentage = (int)(((double)(i + 1) / totalDirectories) * 100);
                OnProgressChanged(percentage, $"正在搜索: {directory}");

                SearchDirectory(directory);
            }
            
            OnProgressChanged(100, "搜索完成");
        }

        /// <summary>
        /// 搜索指定目录
        /// </summary>
        /// <param name="directory">要搜索的目录路径</param>
        private void SearchDirectory(string directory)
        {
            if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
            {
                return;
            }

            try
            {
                // 检查当前目录是否匹配 FileStorage\File\YYYY-MM 模式
                if (DateDirectoryRegex.IsMatch(directory))
                {
                    // 如果匹配，列出该目录下的所有文件
                    var files = Directory.GetFiles(directory)
                        .Select(filePath => new WeChatFile(filePath, false)) // 延迟加载图标以提高性能
                        .ToList();
                    
                    _foundFiles.AddRange(files);
                }

                // 递归搜索子目录
                foreach (string subDirectory in Directory.GetDirectories(directory))
                {
                    SearchDirectory(subDirectory);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 处理没有权限访问的目录
                OnProgressChanged(-1, $"无法访问目录: {directory}");
            }
            catch (Exception ex)
            {
                // 处理其他可能的异常
                OnProgressChanged(-1, $"访问目录 {directory} 时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 触发进度变更事件
        /// </summary>
        /// <param name="percentProgress">进度百分比</param>
        /// <param name="userState">用户状态信息</param>
        protected virtual void OnProgressChanged(int percentProgress, object userState)
        {
            ProgressChanged?.Invoke(this, new ProgressChangedEventArgs(percentProgress, userState));
        }
    }
}
